﻿using System;
using System.ComponentModel;
using System.Diagnostics;

namespace ThePresenter.ViewModel
{
	public abstract class ViewModelBase : INotifyPropertyChanged
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="ViewModelBase"/> class.
		/// </summary>
		public ViewModelBase()
		{
		}

		#endregion

		#region Methods

		/// <summary>
		/// Verify that the property name matches a real, public, instance property on this object.
		/// </summary>
		/// <param name="propertyName">Name of the property.</param>
		[Conditional("DEBUG")]
		[DebuggerStepThrough]
		protected void VerifyPropertyName(string propertyName)
		{
			if (TypeDescriptor.GetProperties(this)[propertyName] == null)
			{
				var msg = string.Format("Invalid property name: '{0}'.", propertyName);

				throw new ArgumentException(msg);
			}
		}

		#endregion

		#region INotifyPropertyChanged Members

		/// <summary>
		/// Occurs when a property value changes.
		/// </summary>
		public event PropertyChangedEventHandler PropertyChanged;

		/// <summary>
		/// Raises the <see cref="E:PropertyChanged"/> event.
		/// </summary>
		/// <param name="propertyName">The name of the property that changed.</param>
		protected virtual void OnPropertyChanged(string propertyName)
		{
			VerifyPropertyName(propertyName);

			var handler = PropertyChanged;

			if (handler != null)
				handler(this, new PropertyChangedEventArgs(propertyName));
		}

		#endregion
	}
}
